package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.Collect;
import com.sk.bilibili.bean.Member;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.DbUtils;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import com.sk.bilibili.utils.RedisUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import com.sk.bilibili.bean.Favorites;
import com.sk.bilibili.mapper.FavoritesMapper;

/**
 * @author 邵康
 * @date 2021/11/25 14:29
 */
@Service
public class FavoritesService extends ServiceImpl<FavoritesMapper, Favorites> {

    @Autowired
    private MinioService minioService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private MemberService memberService;
    private static final String COVER_PATH = "favorites/cover/%s.jpg";
    private static final Pattern COVER_PATTERN = Pattern.compile("/(favorites/cover/.*jpg)");
    private static final String DEFAULT_FAVORITES_NAME ="默认收藏夹";

    public R<Void> add(Favorites favorites) {
        favorites.setMemberId(BSessionUtils.getMemberId());
        QueryWrapper<Favorites> queryWrapper = QueryWrapperUtils.eq(
                "member_id", favorites.getMemberId(), "title", favorites.getTitle());
        if(count(queryWrapper)>0)return R.error(favorites.getTitle()+" 已存在!");
        addFavorites(favorites);
        return R.success();
    }

    public void addFavorites(Favorites favorites) {
        favorites.setCover(minioService.add(favorites.getCoverFile(), COVER_PATH));
        save(favorites);
    }

    public R<Void> delete(Integer id) {
        Favorites temp = getById(id);
        if(temp.getRoot())return R.error("不能删除默认收藏夹");
        minioService.delete(temp.getCover(), COVER_PATTERN);
        collectService.removeCollect(id);
        removeById(id);
        return R.success();
    }

    public R<Void> update(Favorites favorites) {//不要调用子类修改过的
        Favorites temp = super.getById(favorites.getId());
        String cover = minioService.update(COVER_PATH, COVER_PATTERN,temp.getCover(), favorites.getCoverFile());
        favorites.setCover(cover);
        updateById(favorites);
        return R.success();
    }

    public R<IPage<Favorites>> page(Integer page, Integer size) {
        IPage<Favorites> iPage = page(new Page<>(page, size), null);
        return R.success(iPage);
    }

    public R<List<Favorites>> getAll(Integer memberId, Integer size) {
        QueryWrapper<Favorites> queryWrapper;
        int owner = BSessionUtils.getMemberId();
        if(memberId!=null&&memberId!=owner){//若不是自己的只能看公开的
            queryWrapper = QueryWrapperUtils.eq("member_id",memberId,"opened",1);
        }else {
            queryWrapper = QueryWrapperUtils.eq("member_id", owner);
        }
        if(size!=null)queryWrapper.last("limit "+size);
        List<Favorites> list = list(queryWrapper);
        return R.success(list);
    }

    public String getVideoSetCover(Integer id) {
        return baseMapper.getVideoSetCover(id);
    }

    public Integer getDefaultFavorites(int memberId) {
        return baseMapper.getDefaultFavorites(memberId);
    }

    public void changeCount(Integer id, int num) {
        redisUtils.changeNum("Favorites-"+id,"count",num);
    }

    public R<Favorites> getFavorites(Integer id) {
        Favorites favorites = getById(id);
        favorites.getExtra().addExtra(memberService.getById(favorites.getMemberId()));
        return R.success(favorites);
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.CollectService.add'")
    public void handleCollectAdd(BiliBiliEvent<Collect> event){
        Collect collect = event.getData();
        changeCount(collect.getFavoritesId(),1);
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.CollectService.delete'")
    public void handleCollectDelete(BiliBiliEvent<Collect> event){
        Collect collect = event.getData();
        changeCount(collect.getFavoritesId(),-1);
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.CollectService.update'")
    public void handleCollectUpdate(BiliBiliEvent<Collect> event){
        Collect collect = event.getData();
        Collect temp = collectService.getById(collect.getId());
        changeCount(temp.getFavoritesId(),-1);
        changeCount(collect.getFavoritesId(),1);
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.MemberService.register'")
    public void handleMemberRegister(BiliBiliEvent<Member> event){
        Member member = event.getData();
        Favorites favorites = new Favorites();
        favorites.setMemberId(member.getId());
        favorites.setTitle(DEFAULT_FAVORITES_NAME);
        favorites.setRoot(true);
        save(favorites);
    }

}
